import {Button, Descriptions, Divider, Image, Input, message, Modal, Select} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {
  exportDetails,
  exportPay,
  getConfig,
  getPurchaseDetail,
  purchaseList,
  reportOrders,
  revoke,
  setConfig,
  revokePay
} from './service';

import Access from '@/components/Access/Access';
import {CheckSquareOutlined, DownloadOutlined} from "@ant-design/icons";
import CreateForm from "./components/CreateForm";
import "./index.css";
import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import {del} from "@/pages/SupplyChainManagement/PurchaseManagement/UnifyPurchase/UnifyPurchaseList/service";

import {saveFileAs} from "@/utils/utils";
import styles from "@/global.less";

const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [storeArray, setStoreArray] = useState([]);
  const [purchaseDetail, handlePurchaseDetail] = useState(false);
  const [record, setRecord] = useState({});
  const [details, setDetails] = useState({});
  const [outModal, handleOutModal] = useState(false);
  const [outDetailsModal, handleOutDetailsModal] = useState(false);
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]);
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getStore();
  }, []);
  let cancleRowKeys = [];
  const onSelect = (record, selected) => {
    if (!selected) {
      cancleRowKeys = [record.id];
    }
  };
  const onMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.id);
    }
  };
  const onChange = (selectedRowKeys, selectedRows) => {
    if (cancleRowKeys.length) {
      const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
      handleMySelectedRowKeys(keys);
      cancleRowKeys = [];
    } else {
      handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
    }
  };
  const columns = [
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeName',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        true: {
          text: '统采',
          status: 'Success',
        },
        false: {
          text: '地采',
          status: 'Error',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '采购中',
          status: 'Processing',
        },
        1: {
          text: '审批中',
          status: 'Error',
        },
        2: {
          text: '未收货',
          status: 'Error',
        },
        3: {
          text: '未收货',
          status: 'Error',
        },
        4: {
          text: '未收货',
          status: 'Error',
        },
        5: {
          text: '已完成',
          status: 'Success',
        },
        6: {
          text: '未申请付款',
          status: 'Processing',
        },
        7: {
          text: '付款审批中',
          status: 'Processing',
        },
        8: {
          text: '已上库',
          status: 'Success',
        },
        99: {
          text: '已驳回',
          status: 'Error',
        },
        9: {
          text: '已完成',
          status: 'Error',
        },
      },
    },
    {
      title: '采购日期',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '采购日期',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          let end = new Date(value[1]);
          let endDay = end.getDate();
          end.setDate(endDay + 1);
          return {
            startTime: value[0],
            endTime: end,
          };
        },
      },
    },
    {
      title: '报账状态',
      dataIndex: 'reportType',
      valueEnum: {
        true: {
          text: '已报账',
          status: 'Success',
        },
        false: {
          text: '未报账',
          status: 'Error',
        }
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@purchase_getPurchaseDetail"}>
                <Button
                  type="primary"
                  danger
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    setRecord(item);
                    let params = {
                      purchaseId: item.id
                    };
                    getPurchaseDetail(params).then(res => {
                      setDetails(res.data);
                      handlePurchaseDetail(true);
                    });
                  }}
                >
                  详情
                </Button>
              </Access>
              {
                (item.status === 7) ? (<>
                  <Access accessKey={"@purchase_revoke"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        let params = {
                          id: item.id
                        };
                        revokePay(params).then(res => {
                          message.info("撤回成功");
                          actionRef.current.reload();
                        })
                      }}
                    >
                      撤回申请
                    </Button>
                  </Access>

                </>) : (<></>)
              }
              {
                (item.status === 1 || item.status === 2) ? (<>
                  <Access accessKey={"@purchase_revoke"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        let params = {
                          id: item.id
                        };
                        revoke(params).then(res => {
                          message.info("撤销成功");
                          actionRef.current.reload();
                        })
                      }}
                    >
                      撤销
                    </Button>
                  </Access>

                </>) : (<></>)
              }
              {
                item.status === 99 ? (<>
                  <Access accessKey={"@purchase_del"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: '注意',
                          content: '确认要删除此采购单吗',
                          onOk() {
                            let params = {
                              id: item.id
                            };
                            del(params).then(res => {
                              if (res?.code === 0) message.info("删除成功");
                              actionRef.current.reload();
                            })
                          },
                          onCancel() {
                          },
                        });
                      }}
                    >
                      删除
                    </Button>
                  </Access>

                </>) : null
              }
            </div>
          </>
        );
      },
    },
  ];

  const supplierColumns = [
    {
      title: '供应商',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '联系人',
      dataIndex: 'user',
      hideInSearch: true,
    },
    {
      title: '电话',
      dataIndex: 'tel',
      hideInSearch: true,
    },
  ];

  const detailColumns = [
    {
      title: '产品',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '采购数量',
      dataIndex: 'value',
      hideInSearch: true,
    },
    {
      title: '采购成本',
      dataIndex: 'dataPrice',
      hideInSearch: true,
    },
    {
      title: '收货数量',
      dataIndex: 'realStock',
      hideInSearch: true,
    },


  ];
  const outColumns = [
    {
      title: '采购时间',
      dataIndex: 'purchaseDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '采购时间为必选项',
          },
        ],
      },
    },
  ];
  const outDetailsColumns = [

    {
      title: '采购时间',
      dataIndex: 'purchaseDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '采购时间为必选项',
          },
        ],
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  const detailRender = (e) => {

    return <>
      <ProTable
        rowKey="key"
        scroll={{x: 1400}}
        bordered
        dataSource={e.details}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={detailColumns}
      />
    </>
  };


  const getStatusStr = (status) => {
    switch (status) {
      case 0:
        return "采购中";
      case 1:
      case 7:
        return "审批中";
      case 2:
      case 3:
      case 4:
        return "未收货";
      case 5:
        return "已完成";
      case 8:
        return "已上库";
      case 99:
        return "已驳回";
      case 9:
        return "已完成";

    }
  };
  const alertOptionRender = ({selectedRowKeys, selectedRows, onCleanSelected}) => {

    return <>
      <div>
        <Access accessKey={"@purchaseList_reportOrder"}>

        </Access>
        <Button
          key="purchaseList_reportOrder"
          onClick={() => {
            Modal.confirm({
              title: '注意',
              content: '请确认本次已报账数据是否准确!',
              onOk() {
                reportOrders({
                  ids: mySelectedRowKeys
                }).then(res => {
                  message.info("修改成功");
                  handleMySelectedRowKeys([]);
                  actionRef.current.reload();
                })
              },
              onCancel() {
              },
            });
          }}
        >
          <CheckSquareOutlined/>确认已报账
        </Button>
      </div>
    </>;
  };
  return (
    <PageContainer>
      <ProTable
        headerTitle="采购列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => purchaseList({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [
          <Access accessKey={"@purchase_export"}>
            <Button
              key="purchase_export"
              type="primary"
              onClick={() => {
                handleOutModal(true);
              }}
            >
              <DownloadOutlined/> 导出付款列表
            </Button>
          </Access>,
          <Access accessKey={"@purchase_details_export"}>
            <Button
              key="purchase_details_export"
              type="primary"
              onClick={() => {
                handleOutDetailsModal(true);
              }}
            >
              <DownloadOutlined/> 导出地采列表
            </Button>
          </Access>,
          <Access accessKey={"@purchaseList_change_config"}>
            <Button
              key="purchaseList_change_config"
              type="primary"
              onClick={() => {
                getConfig(0).then(res => {
                  let dto = res.data;
                  let curPurchaseNum = dto.purchaseNumber;
                  const popFim = (
                    <div key="popFim">
                      <Input
                        placeholder={(curPurchaseNum > 0) ? curPurchaseNum : "请输入"}
                        style={{width: 140, height: 30, marginLeft: 10}}
                        onChange={(e) => {
                          dto.purchaseNumber = e.target.value;
                        }}
                      />
                    </div>
                  );
                  Modal.confirm({
                    title: '地采频率',
                    content: popFim,
                    icon: '',
                    onOk() {
                      setConfig(dto).then(res => {
                        message.info("修改成功");
                      })
                    },
                    onCancel() {
                    },
                  });
                })

              }}
            >
              地采限制频率
            </Button>
          </Access>
        ]}
        columns={columns}
        rowSelection={{
          fixed: true,
          selectedRowKeys: mySelectedRowKeys,
          onSelect, //用户手动选择/取消选择某行的回调
          onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
          onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
          onChange, //选中项发生变化时的回调
          getCheckboxProps: record => {
            return {
              disabled: (record.status !== 9 || record.reportType)
            };
          },
        }}
        tableAlertOptionRender={alertOptionRender}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />

      <CreateForm
        width={1300}
        onCancel={() => handlePurchaseDetail(false)}
        modalVisible={purchaseDetail}
        btn_view={false}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">采购详情</Divider>
          <Descriptions column={3}>
            <Descriptions.Item label="状态">
              {details ? getStatusStr(details.status) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="总数">
              {details ? details.totalStock : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="总成本">
              {details ? details.totalPrice : '暂无'}
            </Descriptions.Item>
          </Descriptions>

          <ProTable
            headerTitle="详情列表"
            rowKey="id"
            scroll={{x: 1400}}
            bordered
            dataSource={details.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={supplierColumns}
            expandedRowRender={detailRender}
          />
          <Divider orientation="left">收货凭证</Divider>
          <Image.PreviewGroup>
            {
              details.files?.map(img => {
                return <Image key={img.id} width={100} height={100} src={img.img}/>
              })
            }
          </Image.PreviewGroup>
        </div>
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => {
          handleOutModal(false);
        }}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutModal(false);
            exportPay(value).then(res => {
              if (res) {
                saveFileAs(res, '付款记录');
              }
            })
          }}
          rowKey={r => r.id}
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => {
          handleOutDetailsModal(false);
        }}
        modalVisible={outDetailsModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutDetailsModal(false);
            exportDetails(value).then(res => {
              if (res) {
                saveFileAs(res, '地采记录');
              }
            })
          }}
          rowKey={r => r.id}
          bordered
          type="form"
          columns={outDetailsColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
